package com.pine.sunshineelder.bed.service.impl;

import com.github.pagehelper.PageInfo;
import com.pine.sunshineelder.bed.ao.ElderBedAo;
import com.pine.sunshineelder.bed.dto.ElderBedDto;
import com.pine.sunshineelder.bed.service.ElderBedService;
import com.pine.sunshineelder.bed.vo.ElderBedVo;
import com.pine.sunshineelder.common.dao.ElderBedDao;
import com.pine.sunshineelder.common.dto.QueryResult;
import com.pine.sunshineelder.common.entity.ElderBedEntity;
import com.pine.sunshineelder.common.exception.ThisSystemException;
import com.pine.sunshineelder.common.validator.ValidateHelper;
import com.pine.sunshineelder.common.StringHelper;
import static com.pine.sunshineelder.common.validator.ValidateHelper.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 
 * @author 卜涛元
 *
 */

@Service
public class ElderBedServiceImpl implements ElderBedService, StringHelper {
	@Autowired
	ElderBedDao elderBedDao;

	@Override
	public ElderBedVo addElderBed(ElderBedAo ao) throws Exception {
		// 验证参数
		// 非空
		String elderId = $("老人id", ao.getElderId());
		String bedId = $("床位id", ao.getBedId());
		String createUserId = $("创建人id", ao.getCreateUserId());
//		String  creatTime = $("入住时间", ao.getCreatTime().toString());
//		String endTime = $("退住时间", ao.getEndTime().toString());
		String leaveReason = $("退住原因", ao.getLeaveReason());

		// 执行业务逻辑

		ElderBedEntity u = new ElderBedEntity();
		u.setId(uuid());
		u.setElderId(ao.getElderId());
		u.setBedId(ao.getBedId());
		u.setCreateUserId(ao.getCreateUserId());
//		u.setCreateTime(ao.getCreateTime());
//		u.setEndTime(ao.getEndTime());
		u.setLeaveReason(ao.getLeaveReason());

		elderBedDao.insert(u);

		// 组装业务逻辑返回
		ElderBedVo dto = new ElderBedVo();
		dto.setId(u.getId());
		dto.setElderId(u.getElderId());
		dto.setBedId(u.getBedId());
		dto.setCreateUserId(u.getCreateUserId());
//		dto.setCreateTime(toString(u.getCreateTime()));
//		dto.setEndTime(toString(u.getEndTime()));
		dto.setLeaveReason(u.getLeaveReason());

		return dto;
	}

	public static String toString(LocalDateTime time) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
		return time.format(dtf);
	}

	public static String toString(LocalDate date) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		return date.format(dtf);
	}

	/**
	 * 根据id查 老人——床位信息表
	 * 
	 */
	@Override
	public ElderBedVo selectById(String id) throws Exception {

		// 验证参数
		String id1 = ValidateHelper.$("id", id);
		// 执行业务逻辑

		ElderBedEntity u1;
		u1 = elderBedDao.selectById(id1);

		ElderBedVo u = new ElderBedVo();
		System.out.println("++++++++");
		u.setId(u1.getId());
		System.out.println("=========");
		u.setElderId(u1.getElderId());
		u.setBedId(u1.getBedId());
		u.setCreateTime(toString(u1.getCreateTime()));
		u.setEndTime(toString(u1.getEndTime()));
		u.setLeaveReason(u1.getLeaveReason());
		return u;

		// 返回业务结果

	}

	@Override
	public void deleteElderBedById(String id) throws Exception {

		// 验证清理参数
		// 非空
		String id1 = ValidateHelper.$("id", id);

		// 执行业务逻辑

		elderBedDao.delete(id1);

	}

	@Override
	public QueryResult queryByKey(String key, Integer pageNo, Integer pageSize) throws Exception {
		key = trimAsNull(key);
		if (key != null) {
			key = "%" + key + "%";
		}

		if (pageNo == null) {
			pageNo = 1;
		}
		if (pageSize == null) {
			pageSize = 6;
		}
		List<ElderBedEntity> entity = elderBedDao.selectByKey(key, pageNo, pageSize);
		List<ElderBedDto> rows = new ArrayList<ElderBedDto>();
		for(ElderBedEntity e:entity) {
			rows.add(ElderBedDto.of(e));
		}
		
		PageInfo pageInfo = new PageInfo(rows);

		int totalRows = (int) pageInfo.getTotal();

		QueryResult result = new QueryResult();
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setTotalRows(totalRows);
		result.setRows(rows);

		return result;

	}

	@Override
	public ElderBedEntity modifyElderBed(String id, Map<String, String> map) throws Exception {
		// 验证参数
		id = ValidateHelper.$("id", id);
		// 执行业务逻辑
		ElderBedEntity elderBed = elderBedDao.selectById(id);
		if (elderBed == null) {
			throw new ThisSystemException("id.not-exisits", "非法id");
		}

		Map<String, Object> eupdateMap = new HashMap<String, Object>();
		Map<String, Object> aupdateMap = new HashMap<String, Object>();

		// 2.1 老人信息（id）
		String newElderId = trimAsNull(map.get("elderId"));
		if (newElderId != null) {
//	 			if (!Objects.equals(elderBed.getElderId(), newElderId)) {
//	 				// 2.2 账号是否存在
//	 				if (elderBedDao.existElderId(newElderId)) {
//	 					throw new ThisSystemException("ElderId.exists", "老人已存在");
//	 				}
			// 修改旧对象
			elderBed.setElderId(newElderId);
			// 保存要修改的字段
			eupdateMap.put("ElderId", newElderId);
		}
//	 		}

		// 2.2 床位信息（id）
		String newBedId = trimAsNull(map.get("bedId"));
		if (newBedId != null) {
			if (!Objects.equals(elderBed.getBedId(), newBedId)) {

				elderBed.setBedId(newBedId);
				eupdateMap.put("bedId", newBedId);
			}
		}
		// 2.3 创建人信息（id）
		String newCreateUserId = trimAsNull(map.get("createUserId"));
		if (newCreateUserId != null) {
			if (!Objects.equals(elderBed.getCreateUserId(), newCreateUserId)) {

				elderBed.setBedId(newCreateUserId);
				eupdateMap.put("createUserId", newCreateUserId);
			}
		}
		// 2.4 入住时间
		String newCreateTime = trimAsNull(map.get("createTime"));
		if (newCreateTime != null) {
			if (!Objects.equals(elderBed.getCreateTime(), newCreateTime)) {

				elderBed.setBedId(newCreateTime);
				aupdateMap.put("createTime", newCreateTime);
			}
		}
		// 2.4 退住时间
		String newEndTime = trimAsNull(map.get("endTime"));
		if (newEndTime != null) {
			if (!Objects.equals(elderBed.getEndTime(), newEndTime)) {

				elderBed.setBedId(newEndTime);
				aupdateMap.put("endTime", newEndTime);
			}
		}

		// 2.5 退住原因
		String newLeaveReason = trimAsNull(map.get("leaveReason"));
		if (newLeaveReason != null) {
			if (!Objects.equals(elderBed.getLeaveReason(), newLeaveReason)) {

				elderBed.setBedId(newLeaveReason);
				aupdateMap.put("leaveReason", newLeaveReason);
			}
		}
		// 2.3 进行实际的修改
		if (!aupdateMap.isEmpty()) {
			elderBedDao.update(id, aupdateMap);
		}
		if (!eupdateMap.isEmpty()) {
			elderBedDao.update(id, eupdateMap);
		}
		// 3组装业务结果
		return elderBed;
	}

}
